package com.oscarmovie.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oscarmovie.model.Comment;
import com.oscarmovie.model.Paging;

public class CommentDaoImpl extends HibernateDaoSupport implements CommentDao {

	public Comment load(int id) {
		Comment comment = (Comment)getSession().load(Comment.class, id);
		return comment;
	}
	
	public List<Comment> list() {
		Query query = getSession().createQuery("from Comment");
		query.setCacheable(true);
		List<Comment> list = (List<Comment>)query.list();
		return list;
	}
	
	
	public List<Comment> listByAccountId(int accountId) {
		Query query = getSession().createQuery("from Comment");
		query.setCacheable(true);
		List<Comment> list = (List<Comment>)query.list();
		return list;
	}
	
	public void save(Comment comment) {
		getSession().saveOrUpdate(comment);
	}

	public Comment loadByWeiboId(String weiboId) {
		Query query = getSession().createQuery("from Comment comment where comment.weiboId = :weiboId");
		query.setString("weiboId", weiboId);
		Comment comment = (Comment)query.uniqueResult();
		return comment;
	}

	public List<Comment> listByMovieId(int movieId, Paging paging) {
		paging.setTotalCount((int) countByMovieId(movieId));
		Query query = getSession().createQuery("from Comment where movie.id = :mvoieId order by datetime desc");
		query.setInteger("mvoieId", movieId);
		query.setFirstResult(paging.getCurrentRow()-1);
		query.setMaxResults(paging.getPageSize());
		List<Comment> list = (List<Comment>)query.list();
		return list;
	}

	private long countByMovieId(int movieId) {
		Query query = getSession().createQuery("select count(*) from Comment where movie.id = :mvoieId");
		query.setInteger("mvoieId", movieId);
		Long count = (Long) query.uniqueResult();
		return count;
	}

	public List<Comment> listByPersonId(int personId, Paging paging) {
		paging.setTotalCount((int) countByPersonId(personId));
		Query query = getSession().createQuery("from Comment where person.id = :personId order by datetime desc");
		query.setInteger("personId", personId);
		query.setFirstResult(paging.getCurrentRow()-1);
		query.setMaxResults(paging.getPageSize());
		List<Comment> list = (List<Comment>)query.list();
		return list;
	}
	
	private long countByPersonId(int personId) {
		Query query = getSession().createQuery("select count(*) from Comment where person.id = :personId");
		query.setInteger("personId", personId);
		Long count = (Long) query.uniqueResult();
		return count;
	}
}
